package org.l.mybatis.core.handler;

import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.l.mybatis.core.annotation.DBField;

/**
 * Created by 严秋旺 on 2017/8/9.
 */
public class FieldHandler {
    // private Class<?> type;
    private Field field;
    private DBField dbField;
    private String dbName;

    /**
     * @param type 实体类型
     * @param field 实体类型的field
     */
    public FieldHandler(Class<?> type, Field field) {
        // this.type = type;
        this.field = field;
        this.dbField = field.getAnnotation(DBField.class);

        if (dbField == null) {
            this.dbName = field.getName();
        } else {
            String name = dbField.value();

            if (StringUtils.isEmpty(name)) {
                this.dbName = field.getName();
            } else {
                this.dbName = name;
            }
        }
    }

    public boolean isPrimary() {
        return dbField != null && dbField.primary();
    }

    public boolean isIncrement() {
        return dbField != null && dbField.increment();
    }

    /**
     * 获取实体中字段名(实体属性名)
     * @return
     */
    public String getName() {
        return this.field.getName();
    }

    /**
     * 获取表字段名称
     * @return
     */
    public String getDbName() {
        return this.dbName;
    }

    /**
     * 获取表字段实体类型
     * @return
     */
    public Class<?> getType() {
        return field.getType();
    }

    /**
     * 获取表字段数据库类型
     * @return
     */
    public JdbcType getJdbcType() {
        return dbField == null ? null : JdbcType.forCode(dbField.type());
    }
}
